package org.dao.api;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.dao.manager.EntityManagerHolder;


public class Dao <T>{
	private String entityName;
	private Logger logger = Logger.getRootLogger();
	private EntityManager em;
	private EntityTransaction et;
	
	public String getEntityManagerName(){
		return entityName;
	}
	
	public Dao(String entityName) {
		this.entityName = entityName;
		try{ 
			em = EntityManagerHolder.getInstance(entityName);	
			et = em.getTransaction();
			if(!et.isActive()){
				et.begin();	
			}
		}catch(Exception ex){
			em = null;
			et = null;
			logger.log(Level.ERROR, ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	public void commit(){
		if(et == null){
			logger.error("Entity transaction is null");
			return;
		}
		if(et.isActive()){
			et.commit();
		}
		else{
			logger.error("Entity transaction is not activated");
		}
	}
	
	public void roolback(){
		if(et == null){
			logger.error("Entity transaction is null");
			return;
		}
		if(et.isActive()){
			et.rollback();
			et.begin();
		}
		else{
			logger.error("Entity transaction is not activated");
		}
	}
	
	public boolean persist(Object entity){
		if(em == null){
			logger.log(Level.ERROR, "Entity manager is null");
			return false;	
		}
		try{
			if(!et.isActive()){
				et.begin();
			}
			em.persist(entity);
			return true;
		}catch(Exception ex){
			logger.log(Level.ERROR, ex.getMessage());
			return false;
		}
	}
	
	public boolean delete(Object entity){
		if(em == null){
			logger.log(Level.ERROR, "Entity manager is null");
			return false;	
		}
		try{
			if(!et.isActive()){
				et.begin();
			}
			em.remove(entity);
			return true;
		}catch(Exception ex){
			logger.log(Level.ERROR, ex.getMessage());
			return false;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<T> executeQuery(String namedQuery, Tuple... tuples){
		if(em == null){
			logger.log(Level.ERROR, "Entity manager is null");
			return null;	
		}
		try{
			Query query = em.createNamedQuery(namedQuery);
			for(Tuple tuple : tuples){
				query.setParameter(tuple.getKey(), tuple.getValue());
			}
			return query.getResultList();
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> findAll(){
		if(em == null){
			logger.log(Level.ERROR, "Entity manager is null");
			return null;	
		}
		
		Class<?> clazz = (Class<?>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		try{
			Query query = em.createQuery("SELECT u FROM " + clazz.getSimpleName() + " u");
			return query.getResultList();
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}
		return new ArrayList<T>();
	}
	
	@SuppressWarnings("unchecked")
	public T findById(Integer pId){
		if(em == null){
			logger.log(Level.ERROR, "Entity manager is null");
			return null;	
		}
		
		Class<?> clazz = (Class<?>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		try{
			Query query = em.createQuery("SELECT u FROM " + clazz.getSimpleName() + " u where u.id=" + pId);
			return (T) query.getSingleResult();
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}
		return null;
	}
}
